import 'package:flutter/material.dart';
import 'package:star_author/widgets/overlay_widget.dart';

import '../utils/utils.dart';

class BaseDropDownWidget {
  static late OverlayWidget _item;
  static BaseDropDownModel _model = BaseDropDownModel();

  static void show({
    required GlobalKey containerKey,
    required BuildContext context,
    required Widget child,
    required onTap,
    bool multi = false,
  }) {
    GetSize size = GetSize(key: containerKey);
    GetPosition position = GetPosition(key: containerKey);
    double width = size.width;
    double height = size.height;
    double y = position.y;
    Widget content = _BaseDropDownContent(
      top: y + height,
      width: width,
      model: _model,
      child: child,
      onDismissed: () {
        _item.remove();
      },
    );
    _item = OverlayWidget(
      context: context,
      child: content,
    );
    _item.insert();
  }

  static void hide() {
    _model.hide();
  }

  static void hideWithOutAnimation() {
    _item.remove();
  }
}

class BaseDropDownModel with ChangeNotifier {
  void hide() {
    notifyListeners();
  }
}

class _BaseDropDownContent extends StatefulWidget {
  final double? width;
  final double? top;
  final BaseDropDownModel? model;
  final Widget? child;
  final Function? onDismissed;

  _BaseDropDownContent({
    Key? key,
    this.width,
    this.top,
    this.model,
    this.child,
    this.onDismissed,
  }) : super(key: key);

  _BaseDropDownContentState createState() => _BaseDropDownContentState();
}

class _BaseDropDownContentState extends State<_BaseDropDownContent>
    with TickerProviderStateMixin {
  late AnimationController _controller;
  late Animation<double> _animation;

  @override
  void initState() {
    super.initState();
    widget.model!.addListener(_reverse);
    prepareAnimation();
    _controller.forward();
  }

  @override
  void dispose() {
    super.dispose();
    _controller.dispose();
    widget.model!.removeListener(_reverse);
  }

  void _reverse() {
    _controller.reverse();
  }

  void prepareAnimation() {
    _controller = AnimationController(
      vsync: this,
      duration: Duration(milliseconds: 200),
    );
    _animation = CurvedAnimation(
      parent: _controller,
      curve: Curves.easeIn,
    );
    _animation.addStatusListener((status) {
      if (status == AnimationStatus.dismissed) {
        widget.onDismissed!();
      }
    });
  }

  Widget build(BuildContext ctx) {
    return Positioned(
      top: widget.top,
      width: widget.width,
      child: SizeTransition(
        sizeFactor: _animation,
        child: widget.child,
      ),
    );
  }
}
